<template>
  <div class="dn-registration-area">
    <div class="middle main-area">
      <bread-crumb class="bread-crumb-padding" :list="breadCrumb"></bread-crumb>
      <div class="flx-row-bw">
        <div class="left-area box-area">
          <div class="search-area" style="height: 210px">
            <div
              class="placeholder-area c-g f-14"
              v-html="focus || dnText != '' ? '' : placeholder"
            ></div>
            <div class="limit-number c-g f-14">
              <span class="c-o">{{ dnNumber }}</span
              >/500
            </div>
            <Input
              v-model="dnText"
              wrap="hard"
              class="input-area"
              type="textarea"
              maxlength="500"
              :autosize="{ minRows: 10, maxRows: 10 }"
              @on-focus="focus = true"
              @on-keyup="getDNNumber"
              @on-blur="getAvailableDN"
            />
          </div>
          <h2
            class="f-16 f-w-600 c-d2 flx-row-bw-c"
            style="padding-bottom: 5px"
          >
            域名后缀
            <div
              class="c-g f-14 flx-row-s-c open-bottom"
              @click="suffixOpen = !suffixOpen"
            >
              展开
              <div class="icon">
                <div
                  class="dir-icon"
                  :class="{ 'dir-icon-active': suffixOpen }"
                ></div>
              </div>
            </div>
          </h2>
          <div
            class="select-area flx-row-s-c"
            :class="{ 'list-close': !suffixOpen }"
          >
            <div
              :class="{ select: item.isSelect }"
              v-for="(item, index) in selectList"
              :key="index"
              @click="selectItem(index)"
            >
              {{ item.suffix }}
            </div>
          </div>
          <div
            class="user-strong-button normal-button-size"
            style="width: 100px; margin: 10px auto 0"
            @click="search"
          >
            查询
          </div>
          <div v-if="searched" style="position: relative">
            <Spin :withIcon="true" v-if="listLoading"></Spin>
            <h2 class="f-16 f-w-600 c-d2">搜索结果</h2>
            <table class="table-area">
              <tbody>
                <tr v-for="(item, index) in resultList" :key="'r' + index">
                  <td>
                    <div class="line-style-left">
                      <Checkbox
                        style="color: #1c9cdf"
                        v-model="item.select"
                        :disabled="item.isExit == 1"
                      ></Checkbox>
                      <span class="c-d2 f-ell-sin" :title="item.domainName">{{
                        item.domainName
                      }}</span>
                    </div>
                  </td>
                  <td>
                    <div class="line-style">
                      <span class="c-b">{{
                        item.registerStatus == 0 ? "未注册" : ""
                      }}</span>
                    </div>
                  </td>
                  <td>
                    <div class="line-style">
                      <span class="c-o"
                        >{{
                          item.activityPrice != null
                            ? item.activityPrice
                            : item.price
                        }}元/首年</span
                      >
                    </div>
                  </td>
                  <td>
                    <div class="line-style">
                      <div
                        class="user-normal-button form-small-button-size"
                        @click="addOne(index)"
                      >
                        加入购物车
                      </div>
                    </div>
                  </td>
                </tr>
                <template v-for="(item, index) in correctDNList">
                  <tr :key="'c' + index" v-if="!item.search">
                    <td>
                      <div class="line-style-left" style="padding-left: 60px">
                        <span class="c-d2 f-ell-sin" title="">{{
                          item.domainName + item.domainSuffix
                        }}</span>
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="c-g">查询中</span>
                      </div>
                    </td>
                    <td></td>
                    <td></td>
                  </tr>
                </template>
                <tr v-for="(item, index) in errorDNList" :key="'e' + index">
                  <td>
                    <div class="line-style-left" style="padding-left: 60px">
                      <span class="c-d2 f-ell-sin" title="">{{
                        item.domainName
                      }}</span>
                    </div>
                  </td>
                  <td>
                    <div class="line-style">
                      <span class="c-r">{{ item.msg }}</span>
                    </div>
                  </td>
                  <td></td>
                  <td></td>
                </tr>
              </tbody>
            </table>
            <div
              class="flx-row-s-c"
              style="margin-top: 50px"
              v-if="resultList.length > 0"
            >
              <span class="c-b f-16" style="cursor: pointer" @click="selectAll"
                >全选</span
              >
              <div
                class="user-strong-button form-small-button-size"
                style="margin-left: 50px"
                @click="addBatch"
              >
                批量加入购物车
              </div>
            </div>
          </div>
        </div>
        <div class="right-area box-area">
          <div class="title f-14 c-d2">
            购物车{{
              shoppingCartList.length <= 0
                ? ""
                : `（${shoppingCartList.length}）`
            }}
          </div>
          <template v-if="$store.state.user.token">
            <div v-if="shoppingCartList.length > 0" style="position: relative">
              <Spin :withIcon="true" v-if="cartLoading"></Spin>
              <table
                class="small-table-area"
                style="border-bottom: #dcdcdc solid 1px"
              >
                <tbody>
                  <tr v-for="(item, index) in shoppingCartList" :key="index">
                    <td>
                      <div
                        class="line-style"
                        style="justify-content: flex-start"
                      >
                        <span class="c-d2 f-ell-sin" :title="item.tradeName">{{
                          item.tradeName
                        }}</span>
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="c-c"
                          >￥{{
                            item.activityPrice != null
                              ? item.activityPrice
                              : item.price
                          }}</span
                        >
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <div
                          class="line-button"
                          @click="deleteFromCart(item.id, item.tradeName)"
                        >
                          移除
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
              <div class="flx-col-s-e" style="margin-top: 10px">
                <span class="c-o f-14"
                  ><span class="c-d2 f-16">合计：</span>￥ {{ priceSum }}</span
                >
                <router-link
                  class="user-strong-button form-small-button-size"
                  style="margin-top: 10px"
                  to="/po"
                >
                  下单结算
                </router-link>
              </div>
            </div>
            <Empty-State
              style="background-color: #fff; padding-top: 50px"
              v-else
              :noPadding="true"
              content="购物车空空如也，快去添加吧！"
            ></Empty-State>
          </template>
          <div v-else class="login-box c-16 c-d2">
            您还未登录,请完成<span
              @click="clickToLogin"
              class="c-o f-w-200"
              style="padding: 0 8px; cursor: pointer"
              >登录</span
            >了解您所享受的优惠价格
          </div>
        </div>
      </div>
    </div>
    <to-login-modal
      :show.sync="loginModelShow"
      content="需要先登录才能操作！"
      @toLogin="toLogin"
    ></to-login-modal>
  </div>
</template>

<script>
import { debounce, trimStr } from "@/utils/format";
import { checkDomain } from "@/api/data";
import {
  getShoppingCartByType,
  addToShoppingCart,
  deleteFromShoppingCart,
  checkDomainWithToken,
} from "@/api/user";
import { domainSuffix } from "@/utils/publicData";
import Tools from "@/utils/tools";
const DN = /^(?!\.)(?!.*\.$)(?!.*?\.\.).*\..*$/;
const CORRECT = /^(?!-)(?!.*-$)(?!.*?--)[\u4E00-\u9FA5A-Za-z0-9-]+$/;
export default {
  name: "VipDnsearchresult",
  // 接收注入的数据
  inject: ["reload"],
  components: {
    toLoginModal: () => import("_c/modal/toLoginModal/toLoginModal.vue"),
  },
  data() {
    return {
      listLoading: false,
      cartLoading: false,
      breadCrumb: [
        { name: "域名注册", to: "/dnre" },
        { name: "搜索结果", to: "/dnsr" },
      ],
      suffixOpen: false,
      placeholder:
        "请输入域名，每行一个域名；<br/>支持字符为英文、数字、中文、“-”；<br/>“-”不能出现在域名首尾，且不能连续出现；<br/>如输入后缀将被自动忽悠；<br/>每次最多支持500个，多出部分将被忽略；",
      selectList: [],
      suffixSelect: [],
      searched: false,
      // 表单数据
      focus: false,
      dnText: "",
      dnNumber: 0,
      dnSet: new Set(),

      correctDNList: [],
      errorDNList: [],
      resultList: [],

      // 购物车数据
      shoppingCartList: [],

      // 跳转登录
      loginModelShow: false,
    };
  },
  created() {
    if (this.$route.params.suffixList) {
      this.selectList = this.$route.params.suffixList;
      this.suffixSelect = this.$route.params.suffixSelect;
      this.dnText = this.$route.params.dnList.join("\n");
      this.dnNumber = this.$route.params.dnList.length;
      this.dnSet = new Set(this.$route.params.dnList);
      this.getCorrectDN();
    } else {
      let temp = this.$storage.getToLoginData();
      if (temp) {
        this.selectList = temp.suffixList;
        this.suffixSelect = temp.suffixSelect;
        this.dnText = temp.dnList.join("\n");
        this.dnNumber = temp.dnList.length;
        this.dnSet = new Set(temp.dnList);
        this.$storage.setToLoginData("");
        this.getCorrectDN();
      } else {
        this.getDomainSuffix();
      }
    }
    this.getShoppingCart();
  },
  methods: {
    // 获取域名后缀
    async getDomainSuffix() {
      let res = await domainSuffix();
      this.selectList = res;
    },
    selectItem(index) {
      let select = this.selectList[index].isSelect;
      this.selectList[index].isSelect = !select;
    },
    // 查询
    search() {
      let list = [...this.dnSet];
      let suffix = this.selectList.filter((item) => item.isSelect == 1);
      if (list.length <= 0) {
        this.$Message.warning("请至少输入一个域名");
        return;
      }
      if (suffix.length <= 0) {
        this.$Message.warning("请至少输入一个域名后缀");
        return;
      }
      this.$route.params.dnList = list;
      this.$route.params.suffixSelect = suffix;
      this.$route.params.suffixList = this.selectList;
      this.reload();
    },
    // 函数防抖获取输入框中的域名
    getDNNumber: debounce(function () {
      let temp = this.dnText.split("\n");
      this.dnNumber = temp.filter((item) => {
        return !item.match(/^[ ]*$/);
      }).length;
    }, 200),
    // 筛选出有用域名
    getAvailableDN() {
      this.focus = false;
      let temp = this.dnText.split("\n").filter((item) => {
        return !item.match(/^[ ]*$/);
      });
      let dnList = temp.map((item) => trimStr(item));
      this.dnSet = new Set(dnList);
      this.dnText = [...this.dnSet].join("\n");
      this.dnNumber = this.dnSet.size;
    },
    // 筛选出正确的域名
    getCorrectDN() {
      let correctDNList = new Set();
      let errorDNList = new Set();
      for (let i of [...this.dnSet]) {
        let temp;
        if (DN.test(i)) {
          temp = i.split(".")[0];
        } else {
          temp = i;
        }
        if (CORRECT.test(temp)) {
          for (let item of this.suffixSelect) {
            correctDNList.add({
              domainName: temp,
              domainSuffix: item.suffix,
              search: false,
            });
          }
        } else {
          errorDNList.add({
            domainName: temp,
            msg: "域名格式不正确",
          });
        }
      }
      this.correctDNList = [...correctDNList];
      this.errorDNList = [...errorDNList];
      this.searched = true;
      this.getResultList();
    },
    // 查询域名
    getResultList() {
      for (let [index, value] of this.correctDNList.entries()) {
        this.checkDomain(index, value);
      }
    },
    async checkDomain(index, item) {
      let data = {
        domainNameList: [item.domainName + item.domainSuffix],
        domainSuffix: item.domainSuffix,
      };
      let res = this.$token.get()
        ? await checkDomainWithToken(data)
        : await checkDomain(data);
      if (res.code == 200) {
        this.correctDNList[index].search = true;
        if (res.data[0].registerStatus == 0) {
          this.resultList.push({ ...res.data[0], select: false });
        } else {
          this.errorDNList.push({
            domainName: res.data[0].domainName,
            msg: res.data[0].registerStatus == 1 ? "已注册" : "查询失败",
          });
        }
      } else {
        if (res.code === 7000 && !this.toast) {
          this.$Message.warning(res.data);
          this.toast = true;
        }
        this.correctDNList[index].search = true;
        this.errorDNList.push({
          domainName: item.domainName + item.domainSuffix,
          msg: "查询失败",
        });
      }
    },
    // 获取购物车
    async getShoppingCart() {
      if (!this.$token.get()) return;
      this.cartLoading = true;
      // let res = await getShoppingCart();
      let res = await getShoppingCartByType({
        type: 0,
      });
      if (res.code == 200) {
        this.shoppingCartList = res.data;
      }
      this.cartLoading = false;
    },
    // 添加一个到购物车
    async addOne(index) {
      if (!this.$token.get()) {
        this.loginModelShow = true;
        return;
      }
      if (this.resultList[index].isExit == 1) {
        this.$Message.warning("购物车中已存在!");
        return;
      }
      this.listLoading = true;
      let res = await addToShoppingCart({
        tradeNames: [this.resultList[index].domainName],
        type: 0,
      });
      if (res.code == 200) {
        this.$Message.success("添加成功！");
        this.resultList[index].isExit = 1;
        this.resultList[index].select = false;
        this.getShoppingCart();
      }
      this.listLoading = false;
    },
    // 批量添加到购物车
    async addBatch() {
      if (!this.$token.get()) {
        this.loginModelShow = true;
        return;
      }
      let list = this.resultList.filter((item) => item.select);
      if (list.length <= 0) {
        this.$Message.warning("请选择需要加入购物车的域名!");
        return;
      }
      this.listLoading = true;
      let res = await addToShoppingCart({
        tradeNames: list.map((item) => item.domainName),
        type: 0,
      });
      if (res.code == 200) {
        this.$Message.success("添加成功！");
        for (let i in this.resultList) {
          if (this.resultList[i].select) {
            this.resultList[i].isExit = 1;
            this.resultList[i].select = false;
          }
        }
        this.getShoppingCart();
      }
      this.listLoading = false;
    },
    // 选择全部
    selectAll() {
      for (let i in this.resultList) {
        if (!this.resultList[i].select && this.resultList[i].isExit == 0)
          this.resultList[i].select = true;
      }
    },
    // 移除
    deleteFromCart(id, dnName) {
      this.$Modal.confirm({
        title: "移除确认",
        content: "<p>确定要移除此域名吗？</p>",
        onOk: async () => {
          this.cartLoading = true;
          let res = await deleteFromShoppingCart([id]);
          if (res.code == 200) {
            this.$Message.success("移除成功！");
            this.getShoppingCart();
            for (let i in this.resultList) {
              if (this.resultList[i].domainName == dnName) {
                this.resultList[i].isExit = 0;
                break;
              }
            }
          }
          this.cartLoading = false;
        },
      });
    },
    // 去登陆
    toLogin() {
      let list = [...this.dnSet];
      let suffix = this.selectList.filter((item) => item.isSelect == 1);
      this.$storage.setToLoginData({
        suffixList: this.selectList,
        suffixSelect: suffix,
        dnList: list,
      });
      window.location.href = "/login";
    },
    // 点击跳转去登陆
    clickToLogin() {
      this.$storage.setToLoginRoute(this.$route.fullPath);
      this.toLogin();
    },
  },
  computed: {
    priceSum() {
      let sum = 0;
      for (let item of this.shoppingCartList) {
        sum = Tools.accAdd(
          sum,
          item.activityPrice == null ? item.price : item.activityPrice
        );
      }
      return sum;
    },
  },
};
</script>

<style lang="scss" scoped>
.dn-registration-area {
  background-color: #f7f7f7;
  padding-bottom: 20px;
}
.left-area {
  width: 750px;
  .search-area {
    position: relative;

    .input-area {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 100%;
      background: none !important;
    }
    .limit-number {
      background-color: #fff;
      position: absolute;
      right: 20px;
      bottom: 20px;
      z-index: 2;
    }
  }
  .placeholder-area {
    @include size(100%, 136px);
    padding: 10px 20px;
  }
  .table-area tr:nth-child(even) {
    background-color: #f9fafb;
  }
  .table-area tr:nth-child(odd) {
    background-color: #fff;
  }
  .select-area {
    margin-top: 20px;
    flex-wrap: wrap;

    div {
      width: 93px;
      height: 30px;
      font-size: 14px;
      color: #3d3d3d;
      background-color: #efefef;
      border: 2px solid transparent;
      text-align: center;
      line-height: 26px;
      transition: background-image 0.3s, border-color 0.3s,
        background-color 0.3s;
      cursor: pointer;
      margin-bottom: 9px;
      margin-right: 4px;
      margin-left: 4px;

      &:hover {
        border-color: #fa6335;
        background-color: #fff;
      }

      &.select {
        border-color: #fa6335;
        background-color: #fff;
        @include bg-setting("select", 18px 18px, right bottom);
      }
    }
  }
  h2 {
    margin: 10px 0 26px;
    border-bottom: 1px solid #dcdcdc;
    line-height: 30px;
  }
}
.right-area {
  width: 435px;

  .title {
    padding-left: 25px;
    @include bg-setting("shopping", 18px 19px, left center);
    margin-bottom: 10px;
  }
  .line-button {
    @include h-c(null, null, $mainColor, $color-main-8);
    cursor: pointer;
    font-size: 14px;
  }
}
.box-area {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(#000, 0.1);
  padding: 26px 21px 30px;
}
.open-bottom {
  cursor: pointer;
  .icon {
    width: 15px;
    padding-left: 3px;

    .dir-icon {
      @include size(12px, 6px);
      @include bg-setting("g-down");
      transform: rotate(0);
      transition: transform 0.3s, background-image 0.3s;
    }
    .dir-icon-active {
      transform: rotate(-180deg);
    }
  }

  &:hover {
    color: $mainColor;

    .dir-icon {
      @include bg-setting("o-down");
    }
  }
}
.list-close {
  max-height: 155px;
  overflow: hidden;
}
.login-box {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px dashed #dcdcdc;
  margin-top: 20px;
}
</style>
